package com.caimiao.miao.page.master.system.lottery;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

import com.caimiao.miao.library.utils.tip.ToastUtil;

public class UsbTestHost {
    private static final String ACTION_USB_PERMISSION = "com.caimiao.maio.USB_PERMISSION";
    private PendingIntent mPermissionIntent;

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            ToastUtil.show("device =" + device);
                        }
                    } else {
                        ToastUtil.show("用户不允许USB访问设备，程序退出！");
                    }
                }
            }
        }
    };

    public UsbTestHost(Context context) {
        mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        //注册USB设备权限管理广播
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        context.registerReceiver(usbReceiver, filter);
    }

    public void close(Context context) {
        context.unregisterReceiver(usbReceiver);
    }
}
